package bma.common.langutil.log;

import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

import bma.common.langutil.core.DateTimeUtil;

public class LogLatch {

	// config
	private int silencePeriod = 5 * 60 * 1000;

	// runtime
	private Map<String, Long> logMap;

	public LogLatch() {
		super();
		logMap = Collections.synchronizedMap(new TreeMap<String, Long>());
	}

	public int getSilencePeriod() {
		return silencePeriod;
	}

	public void setSilencePeriod(int silencePeriod) {
		this.silencePeriod = silencePeriod;
	}

	public void setSilencePeriodValue(String s) {
		this.silencePeriod = (int) DateTimeUtil.parsePeriodValue(s,
				this.silencePeriod);
	}

	public boolean isLogable(String key) {
		Long r = this.logMap.get(key);
		if (r == null
				|| System.currentTimeMillis() - r.longValue() > silencePeriod) {
			return true;
		}
		return false;
	}

	public boolean checkLogable(String key) {
		if (isLogable(key)) {
			this.logMap.put(key, System.currentTimeMillis());
			return true;
		}
		return false;
	}
}
